/*
Copyright (c) 2013 Mihail Volkov

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#ifndef HTMD_SAMPLE_UNITS_H_INCLUDED
#define HTMD_SAMPLE_UNITS_H_INCLUDED

#include "quickstart_unit.h"
#include <list>
#include <deque>

#ifndef DISABLE_HTMD

/// @brief Test console that features output of text messages
/// (HtMdTestConsole::printf) and execution of commands typed
/// at the client console (HtMdTestConsole::CommandHandler).
/// Is a singleton. Create only one single instance per whole
/// program.
///
/// Commands sent to the client console are the Printf-ed
/// strings as is.
/// Commands from the client are parsed in form
/// "command_name ...the rest of the string are arguments..."
/// and are passed to CommandHandler-s registered for command
/// name "command_name".
class HtMdTestConsole: public HtMdQuickStartUnit
{
	static HtMdTestConsole *spInstance;

public:
	static const int MAX_BUFFER_SIZE = 4096;
	using HtMdQuickStartUnit::isClientReady; // this is useful public

private:
	// commands related stuff
	class CommandBase
	{
		int mRefCount;
	public:
		std::string mName,mHelp;
		virtual void operator () (const std::string &) = 0;
		CommandBase (const std::string &name,const std::string &help):
			mRefCount (0), mName (name), mHelp (help) {}
		virtual ~CommandBase () {}
		void addRef () { ++mRefCount; }
		bool dropRef ()
		{
			if (--mRefCount<=0)
			{ delete this; return true; }
			else return false;
		}
	};

	template <class F>
	class FunctionalCommand: public CommandBase
	{
		F mFunctional;
	public:
		FunctionalCommand (const std::string &name,
			F f,const std::string &help):
			CommandBase (name,help), mFunctional (f) {}
		void operator () (const std::string &args)
		{ mFunctional (args); }
	};

	template <class T,class MF>
	class MemberFunctionalCommand: public CommandBase
	{
		T *mpObject;
		MF mMember;
	public:
		MemberFunctionalCommand
			(const std::string &name,T *pObj,MF mf,
			const std::string &help):
			CommandBase (name,help),
			mpObject(pObj), mMember (mf) {}
		void operator () (const std::string &args)
		{ (mpObject->*mMember) (args); }
	};

	std::map<std::string,CommandBase *> mCommands;
	static void registerCommand (const std::string &name,CommandBase *);
	static void unregisterCommand (const std::string &name,CommandBase *);

	std::map<std::string,bool> mChansEnabled;
	std::map<std::string,bool>::iterator mCurChannel;

protected:
	// HtMdUnit re-implementation
	void onClientConnected ();
	void onClientDisconnected ();
	void onClientTurnIn ();
	void onClientSuspended ();

	// HtMdQuickStartUnit implementation
	void onReceiveString
		(const std::string &,bool overflowTruncated);
	std::string getSentOverflowWarningString ();

public:
	HtMdTestConsole ();
	~HtMdTestConsole ();

	static void setPrintfChannel (const char *channel);
	static void printf (const char *format,...);

	/// @brief Command handler. Create an instance of this object to
	/// register a named command. The command will stay registered
	/// as long as this instance (or any of its copies) is alive.
	class CommandHandler
	{
		friend class HtMdTestConsole;
		CommandBase *mpCmd;

	public:
		CommandHandler (): mpCmd (NULL) {}
		CommandHandler (const CommandHandler &src): mpCmd (src.mpCmd)
		{
			if (mpCmd!=NULL) mpCmd->addRef ();
		}
		~CommandHandler ()
		{
			if (mpCmd!=NULL)
			{
				std::string name = mpCmd->mName;
				if (mpCmd->dropRef ())
					unregisterCommand (name,mpCmd);
			}
		}
		CommandHandler &operator = (const CommandHandler &src)
		{
			if (src.mpCmd!=mpCmd)
			{
				if (mpCmd!=NULL)
				{
					std::string name = mpCmd->mName;
					if (mpCmd->dropRef ())
						unregisterCommand (name,mpCmd);
				}
				mpCmd = src.mpCmd;
				if (mpCmd!=NULL) mpCmd->addRef ();
			}
			return *this;
		}

		/// @brief Form of command to register an action performed by
		/// a static function or a functional object.
		/// @param name Name the command will be registered under.
		/// In the console, it will be accessible via
		/// "commandName args...".
		/// @param F Action to perform on the command, a function or a
		/// functional object of signature
		/// void(const std::string &commandArguments).
		template <class F>
		CommandHandler (const std::string &name,F f)
		{
			mpCmd = new FunctionalCommand<F> (name,f,
				name+": does something");
			mpCmd->addRef ();
			registerCommand (name,mpCmd);
		}

		/// @brief Form of command to register an action performed by
		/// a static function or a functional object.
		/// @param name Name the command will be registered under.
		/// In the console, it will be accessible via
		/// "commandName args...".
		/// @param pObj Pointer to the object. The object must stay
		/// alive while this command is registered.
		/// @param Action to perform on the command, a member function
		/// of pObj of signature
		/// void(const std::string &commandArguments).
		template <class T,class MF>
		CommandHandler (const std::string &name,
			T *pObj,MF member)
		{
			mpCmd = new MemberFunctionalCommand<T,MF> (name,
				pObj,member,
				name+": does something");
			mpCmd->addRef ();
			registerCommand (name,mpCmd);
		}

		void setHelp (const std::string &help)
		{
			if (mpCmd!=NULL) mpCmd->mHelp = help;
		}
	};
};

/// @brief Test file browser that allows to browse dirs tree under
/// a given starting point, to upload and to download files.
/// Is a singleton. Create only one instance at once. The instance
/// is assumed to live for a short time, and flow of the program
/// is assumed to suspend for the time it runs in order to provide
/// consistent exclusive access to files.
class HtMdTestFileBrowser: public HtMdQuickStartUnit
{
	static HtMdTestFileBrowser *spInstance;

	class Uploader: public HtMdQuickFileUploader
	{
		std::string mDir,mFile;
	public:
		void prepareDir (const std::string &dir)
		{ mDir = dir; mFile = "file"; }
		std::string getFile () { return mFile; }
		std::string acceptIncomingName
			(const std::string &initialName,
			const std::string &userName);
	};

	bool mFinished;
	Uploader mFileUploader;
	HtMdQuickFileDownloader mFileDownloader;
	std::list<std::string> mPath;
	std::deque<std::string> mDirs,mFiles,
		mDirsLatin,mFilesLatin;
	std::string mBasePath;

	enum FileOp
	{
		FO_NONE,
		FO_UPLOAD,
		FO_DOWNLOAD
	} mCurFileOp;
	std::string mCurFileName;

	std::string getCurrentPath ();
	std::string getCurrentRootRelativePath ();
	void refresh (const std::string &status);

protected:
	void onClientConnected ();
	void onClientDisconnected ();
	void onClientSuspended ();
	// handling onClientTurnIn is not required, the HtMdTestFileBrowser
	// is entirely driven by client commands and does nothing on its
	// own initiative

	// HtMdQuickStartUnit implementation
	void onReceiveString (const std::string &,bool);
	std::string getSentOverflowWarningString () { return ""; }

	void onUpdate ();

public:
	/// @brief Create the file browser unit, set it to given
	/// path as the root of browsing
	HtMdTestFileBrowser (const std::string &basePath);
	~HtMdTestFileBrowser ();

	/// @brief Returns true if the browser has finished working,
	/// can be removed and the program can be resumed
	bool isFinished ();
};

#define HTMD_PRINTF(channel,args) do\
{ HtMdTestConsole::setPrintfChannel (#channel);\
HtMdTestConsole::printf args; } while (0)

#else

#define HTMD_PRINTF(chan,args)

#endif // DISABLE_HTMD

#endif // HTMD_SAMPLE_UNITS_H_INCLUDED
